$(document).on("pagecreate", function(event) {
	$(".fromNow").each(function() {
		if ($(this).data("fromNow") === undefined) {
			$(this).data("fromNow", $(this).text());
		}
	});
	updateMoment();

	if (typeof jsf !== 'undefined') {
		jsf.ajax.addOnEvent(function onStatusChange(data) {
			if (data.status === "begin") {
				document.body.style.cursor = 'wait';
				$.mobile.loading("show");
			} else {
				document.body.style.cursor = 'auto';
				$.mobile.loading("hide");
			}
		});
	}
});

function updateMoment() {
	$(".fromNow").each(function() {
		$(this).text(fromNow($(this).data("fromNow")));
	});
	window.setTimeout(updateMoment, 1000);
}

function fromNow(dateString) {
	var date = new Date(dateString);
	var now = new Date();
	var interval = ~~((date.getTime() - now.getTime()) / 1000 + 1);
	var future = (interval > 0);
	interval = Math.abs(interval);
	if (interval < 60) {
		return formattedMoment(interval, 'seconds', future);
	}
	interval = ~~(interval / 60);
	if (interval < 60) {
		return formattedMoment(interval, 'minutes', future);
	}
	interval = ~~(interval / 60);
	if (interval < 24) {
		return formattedMoment(interval, 'hours', future);
	}
	interval = ~~(interval / 24);
	if (interval < 7) {
		return formattedMoment(interval, 'days', future);
	}
	if (interval < 30) {
		return formattedMoment(~~(interval / 7), 'weeks', future);
	}
	if (interval < 365) {
		return formattedMoment(~~(interval / 30), 'months', future);
	}
	interval = ~~(interval / 365);
	return formattedMoment(interval, 'years', future);
}

function formattedMoment(interval, time, future) {
	if (future) {
		return "in " + interval + " " + time;
	}
	return interval + " " + time + " ago";
}
